package com.game.framework.utils;

import java.lang.reflect.Field;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.springframework.beans.BeanUtils;

/**
 * BeanUtil
 * @author Liyuan
 */

public class BeanUtil {
	
	/**
	 * clone
	 * @param object
	 * @return
	 */
	public static Object clone(Object object){
		if(object == null) return null;
		Object newObject = null;
		try{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			oos.close();
			ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
			ObjectInputStream ois = new ObjectInputStream(bais);
			newObject = ois.readObject();
			ois.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return newObject;
	}
	
	/**
	 * copyProperties
	 * @param from
	 * @param to
	 */
	public static void copyProperties(Object source, Object target) {
		if (source == null || target == null) return;
		try {
			BeanUtils.copyProperties(source, target);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * copySameProperties
	 * @param from
	 * @param to
	 */
	public static void copySameProperties(Object source, Object target) {
		if (source == null || target == null) return;
		
		Class fromClass = source.getClass();
		Class toClass = target.getClass();

		Field[] oneFields = fromClass.getDeclaredFields();
		Field[] twoFields = toClass.getDeclaredFields();

		for (Field one : oneFields) {
			one.setAccessible(true);
			for (Field two : twoFields) {
				two.setAccessible(true);
				if (one.getName().equals(two.getName())
						&& one.getType().getName().equals(two.getType().getName())) {
					try {
						two.set(target, one.get(source));
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
}
